<template>
  <div class='m-customerDetail'>
    <el-form class="form m-customerDetail_form" ref='form' :inline='true' label-width="120px" :model="form" :rules='rules'>
      <el-form-item class='module-form-item' label="手机号码：" prop='phone'>
        <el-input type="phone" placeholder="手机号码" v-model="form.phone" class='form-content'></el-input>
        <el-button type='primary' @click='checkIsHaveSamePhone' style='margin-left: 20px'>检查存在</el-button>
      </el-form-item>
      <el-form-item class='module-form-item' label="客户姓名：" prop='name'>
        <el-input type="text" placeholder="请输入6位以上数字与字母组合" v-model="form.name" class='form-content'></el-input>
      </el-form-item>
      <!-- <el-form-item class='module-form-item' label="意向类别：" prop='dues'>
        <a-select v-model='form.dues' :options='duesList' class='form-content' />
      </el-form-item> -->
      <el-form-item class='module-form-item' label="客户类型：" prop='type'>
        <a-select v-model='form.type' :options='typeList' class='form-content' />
      </el-form-item>
      <!-- <el-form-item label='业务员：' class='module-form-item' v-if='!isCreate'>
        {{ staff_name }}
      </el-form-item> -->
      <!-- <el-form-item class='module-form-item' label="所属地区：" prop='areaId'>
        <a-select v-model='province' @change='getAddProvince' :options='provinceList' />
        <a-select style='margin-left: 20px' v-model='city' @change='getAddCity' :options='cityList' />
        <a-select style='margin-left: 20px' v-model='area' :options='areaList' />
      </el-form-item> -->
      <el-form-item class='module-form-item' label="备注：">
        <el-input type="text" class='form-content' v-model="form.remark"></el-input>
      </el-form-item>
      <el-form-item class='module-form-item' label="创建日期：" v-if='!isCreate'>
        {{ createdAt | filterStringTime }}
      </el-form-item>
      <el-form-item class='module-form-item' label="修改日期：" v-if='!isCreate'>
        {{ updatedAt | filterStringTime }}
      </el-form-item>
      <el-form-item class='module-form-item' label='选择属性：'>
        <!-- <List aType='3' ref='attrList' :limitCreateNum='1' :isShowSelectBox='false' @getSku='getSku' @updateSku='getSku' /> -->
        <el-button @click='selectAttr'>选择属性</el-button><el-button @click='addAttr'>添加属性</el-button>
      </el-form-item>
    </el-form>
    <attr-form ref='attrForm' aType='3' />
    <div class='module-form-item' align='left' style='width: 100%;'>
      <el-button type="primary" @click="reset">重置</el-button>
      <el-button type="primary" @click="confirm">{{ isCreate ? '添加客户' : '确认修改' }}</el-button>
    </div>

    <staff-dialog ref='staffDialog' @getData='getStaff' />
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import AttrForm from '@/components/business/Form'
import uAttr from '@/module/customer/u-attr'
// import attrMixin from '@/mixins/attrs'
import staffDialog from '@/components/business/StaffsDialog'
import CUSTOMER_TYPE from '@/api/customer'

/**
 * attrList 数组列表对象结构
 * @param {Array} classes -- 一级分类
 * @param {Array} classes2 -- 二级分类
 * @param {Array / String} content -- 选择的分类 / 输入框内容
 * @param {String} skuId -- 非必选的标识
 * @param {String} id -- 属性 id
 * @param {String} name -- 属性 name
 */

export default {
  name: 'u-customer_detail',

  data() {
    return {
      form: {
        phone: '',
        name: '',
        dues: '',
        areaId: '',
        // seller: '',
        remark: '',
        type: '2'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正规的手机号码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度至少 2 - 10 个字符', trigger: 'blur' }
        ]
        // dues: [
          // { required: true, message: '请选择意向类别', trigger: 'blur' }
        // ],
        // areaId: [
        //   { required: true, message: '请选择地区', trigger: 'blur' }
        // ]
        // remark: [
        //   { required: true, message: '请输入备注', trigger: 'blur' }
        // ]
      },
      sellerName: '',
      ifRequesting: false,
      provinceList: [],
      cityList: [],
      areaList: [],
      province: '',
      city: '',
      area: '',
      attrList: [],
      duesList: [],
      updatedAt: '',
      createdAt: '',
      staff_name: '',
      isCreate: true,
      typeList: Object.keys(CUSTOMER_TYPE).map(v => ({
        label: CUSTOMER_TYPE[v],
        value: v
      }))
    }
  },

  components: {
    AttrForm,
    staffDialog,
    uAttr
  },

  // mixins: [attrMixin],

  async mounted() {
    const { id, type } = this.$route.query
    console.log(type)
    this.isCreate = type !== 'set'
    this.id = id || ''
    // this.getAddress()
    // this.getDues()
    await this.getAttributes()
    if (id && !this.isCreate) {
      this.getInfo(id)
      // this.getLoginInfo()
    }
  },

  watch: {
    province() {
      this.getArrId()
    },
    city() {
      this.getArrId()
    },
    area() {
      this.getArrId()
    }
  },

  methods: {
    ...mapMutations(['setTabRoutes']),

    getArrId() {
      if (this.area) {
        this.form.areaId = this.area
      } else if (this.city) {
        this.form.areaId = this.city
      } else if (this.province) {
        this.form.areaId = this.province
      }
    },

    async getAddress() {
      const { code, data } = await this.$api.utilsGetAddress()
      if (code === 0) {
        this.provinceList = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getAddProvince(value) {
      const { code, data } = await this.$api.utilsGetAddress({ aId: value })
      if (code === 0) {
        this.cityList = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
        console.log(this.cityList)
      }
    },

    async getAddCity(value) {
      const { code, data } = await this.$api.utilsGetAddress({ aId: value })
      if (code === 0) {
        this.areaList = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async create() {
      if (this.ifRequesting) return
      this.ifRequesting = true
      const form = this.form
      const params = {
        aFirmId: this.aFirmId,
        aShortName: form.name,
        aFullName: form.name,
        aPhone: form.phone,
        // aDueId: form.dues,
        aAreaId: form.areaId,
        aMemo: form.remark,
        // aSalesId: form.seller,
        aId: this.id
      }
      if (form.type || form.type === 0) {
        params.aType = form.type
      }
      params.aAttrs = this.$refs.attrForm.$formatOutputData()
      const { code, data } = await this.$api[this.isCreate ? 'crmCreate' : 'crmUpdate'](params)
      this.ifRequesting = false
      if (code === 0) {
        console.log(data)
        this.__notify(this.isCreate ? '添加成功' : '修改成功')
        this.setTabRoutes({ type: 'remove', obj: this.getRouterInfoAccordingName('customerAdd') })
        this.setTabRoutes({ type: 'add', obj: this.getRouterInfoAccordingName('customer') })
        this.$router.push({ name: 'customer' })
      } else if (code !== 1) {
        // // 有重复
        // this.$confirm('该客户已存在，点确定修改该客户信息？', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   this.isCreate = false
        //   this.create()
        // }).catch(() => {
        //   this.$message({ type: 'info', message: '已取消该操作' })
        // })
      }
    },

    showSetPwdBox() {
      this.dialogVisible = true
    },

    async getDues() {
      const { code, data } = await this.$api.crmGetDues({
        aFirmId: this.aFirmId
      })
      if (code === 0) {
        this.duesList = data.list.map(v => ({
          label: v.name,
          value: v.id
        }))
      }
    },

    confirm() {
      if (this.ifRequesting) return
      this.$refs.form.validate((valid) => {
        if (!valid) return
        if (this.form.newPwd !== this.form.checkNewPwd) {
          this.__notify('警告', '新密码与确认密码不相同', 'warning')
          return
        }
        this.create()
      })
    },

    reset() {
      this.$refs.attrForm.$clear()
      this.$refs.form.resetFields()
      this.province = ''
      this.city = ''
      this.area = ''
      this.form.type = 2
      // this.attrList = []
    },

    // attr
    async getAttributes() {
      const { code, data } = await this.$api.utilsGetAllClasses({
        aMerchantId: this.aFirmId,
        aType: '3'
      })
      if (code === 0) {
        this.$refs.attrForm.$formatAttrAndClassData(data.list)
      }
    },

    async getLoginInfo() {
      const { code, data } = await this.$api.crmGetLoginInfo()
      if (code === 0) {
        this.staff_name = data.staff_name
      }
    },

    async getInfo(aId) {
      const { code, data } = await this.$api.crmGetIntentInfo({
        aId
      })
      if (code === 0) {
        console.log(data)
        // 填充数据
        this.form.phone = data.phone
        this.form.name = data.short_name
        this.form.dues = data.due_id
        this.form.remark = data.memo
        this.form.seller = data.sales_id
        this.sellerName = data.sales_name
        this.createdAt = data.create_time
        this.updatedAt = data.update_time
        // 获取地区数据
        const areas = data.areas
        if (areas[0]) {
          this.province = areas[0].id
        }
        if (areas[1]) {
          this.city = areas[1].id
          this.getAddProvince(this.province)
        }
        if (areas[2]) {
          this.area = areas[2].id
          this.getAddCity(this.city)
        }
        // 根据必须和非必须，进行分开格式化
        this.$refs.attrForm.$formatDetail(data)
      }
    },

    async checkIsHaveSamePhone() {
      const aPhone = this.form.phone
      if (!window.$tools.regexp.phone.test(aPhone)) {
        return this.__notify('警告', '请输入正确的手机号', 'warning')
      }
      const { code, data } = await this.$api.crmCheckIntents({
        aFirmId: this.aFirmId,
        aType: 0,
        aPhone
      })
      if (code === 0 && data.exists === 1) {
        // this.reset()
        // await this.getAttributes()
        // // 获取对应
        // this.id = data.list[0].id
        // this.getInfo(data.list[0].id)
        this.__notify('查询手机号', '已存在该手机号的客户', 'info')
      } else {
        this.__notify('查询手机号', '暂无此手机号')
      }
    },

    closeAutoAttr(index) {
      let _i = index
      this.attrList.forEach((v, i) => {
        if (i < index && !v.skuId) _i -= 1
      })
      this.attrList.splice(index, 1)
      this.$refs.attrList.closeSku(_i)
    },

    showStaffDialog() {
      this.$refs.staffDialog.show()
    },

    getStaff(data) {
      console.log(data)
      this.form.seller = data.staff_id
      this.sellerName = data.name
    },

    selectAttr() {
      this.$refs.attrForm.$openSelectAttrBox()
    },

    addAttr() {
      this.$refs.attrForm.$openCreateAttrBox()
    }
  }
}
</script>

<style lang='less'>
.m-customerDetail {
  &_form {
    display: flex;
    flex-wrap: wrap;
    display: flex;
    .module-form-item {
      width: 50%;
      margin-right: 0;
      display: flex;
      align-items: center;
      .el-form-item__content {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .el-select {
        flex: 1;
      }
    }
  }
}
</style>